package com.itstherules.jmsunit;

import javax.jms.Message;

import com.itstherules.jmsunit.managers.QueueManager;
import com.itstherules.jmsunit.mock.store.CompositeExpectation;
import com.itstherules.jmsunit.mock.store.Store;

public final class JmsStandaloneMock extends JmsMock {
	
	private boolean play = true;
	
	public JmsStandaloneMock(QueueManager queueManager) throws Exception {
		super(queueManager);
	}
	
	public Store when() {
		Store store = new Store();
		mall.add(store);
		return store;
	}
	
	public final void play() throws Exception {
		while (play) {
			for (Store store : mall) {
				try {
					Message message = receive(store);
					CompositeExpectation expectations = store.getWithExpectations();
					if(haveExpectationsPassed(message, expectations)){
						send(store);
					}
				} catch (AssertionError e) {
					System.out.println("Timed out when reading from queue "+store.getThrough()+", trying again with the next stored directive");
				}
			}
		}
		queueManager.close();
	}

	private boolean haveExpectationsPassed(Message message, CompositeExpectation expectations) {
		try {
			expectations.compute(message);
		} catch(AssertionError e) {
			return false;
		}
		return true;
	}
}
